<template>
  <el-dialog
    title="选择地址"
    :model-value="modelValue"
    :destroy-on-close="true"
    center
    :before-close="mapFn.closePopup"
    width="50%"
  >
    <iframe
      width="100%"
      style="height: 60vh; border: none"
      src="https://mapapi.qq.com/web/mapComponents/locationPicker/v/index.html?search=1&type=1&key=D3JBZ-IHNEU-4YLV5-B5PMB-B2GG6-WCFPK&referer= 品客"
    ></iframe>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="mapFn.closePopup">取 消</el-button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <el-button type="primary" @click="mapFn.submitMap">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import { ElMessage } from "element-plus";
import { reactive } from "vue";

export default {
  name: "chooseAddress",
  components: {},
  emits: ["submitCompleted", "update:modelValue"],
  setup(props, content) {
    // 默认数据备份，以便重置或恢复
    const { $data: mapData, $fn: mapFn } = initData(content);
    window.addEventListener('message', function(event) {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      var loc = event.data;
      if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
          // console.log(344444, loc);
          mapData.map_data.eventsAddress = loc.poiaddress;
          mapData.map_data.latitude = loc.latlng.lat;
          mapData.map_data.longitude = loc.latlng.lng;
          mapData.map_data.poiname = loc.poiname;
      }
    }, false);
    return {
      mapData,
      mapFn,
      modelValue: props.modelValue,
    };
  },
  props:{
    modelValue: Boolean,
  }
};

    
function initData(content) {
  const $data = reactive({
    map_data: {
      eventsAddress: "",
      longitude: "",
      latitude: "",
      poiname: ""
    },
  });

  const $fn = {
    closePopup() {
      $data.map_data = {
        eventsAddress: "",
        longitude: "",
        latitude: "",
        poiname: ""
      };
      content.emit("update:modelValue", false);
    },
    //地图选点确定
    submitMap() {
      if ($data.map_data.latitude === "" || $data.map_data.longitude === "") {
        ElMessage.error("请先选择地址！");
        return;
      }
      console.log(555, $data.map_data);
      // console.log(content)
      content.emit("submitCompleted",$data.map_data);
      $fn.closePopup()
    },
    show(lat,lng){
      let mat_url = $data.map_data.url;
      if(lat && lng){
          mat_url += '&coord=' + lat + ',' + lng;
      }
      $data.map_src = mat_url;
      $data.mapLocationPicker = true
    },
  };

  return {
    $data,
    $fn,
  };
}
</script>